package com.guoxin.designpattern.chapter6;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @author guoxin
 * @date 2019/9/4
 */
public class WriterWorker extends Thread {
    private final ShareData shareData;
    private final String filler;
    private int index = 0;

    public WriterWorker(ShareData shareData, String filler) {
        this.shareData = shareData;
        this.filler = filler;
    }

    @Override
    public void run() {
        try {
            for (; ; ) {
                char c = nextChar();
                shareData.write(c);
                Thread.sleep(ThreadLocalRandom.current().nextInt(1000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private char nextChar() {
        char c = filler.charAt(index);
        index++;
        if (index >= filler.length()) {
            index = 0;
        }
        return c;
    }
}
